<template>
  <section class="todoapp">
    <hm-header @add-item-event="addItem"></hm-header>
    <hm-main
      :list="newList"
      @remove-item-event="removeItem"
      @change-state-event="changeState"
      @change-all-event="changeAll"
    ></hm-main>
    <hm-footer :list="list" :status="status" @clear-all-event="clearAll" @status-event='status=$event'></hm-footer>
  </section>
</template>

<script>
const obj ={
  '#/':'all',
  '#/active':'undone',
  '#/completed':'done'
}
import HmHeader from "./components/hm-header.vue";
import HmMain from "./components/hm-main.vue";
import HmFooter from "./components/hm-footer.vue";
export default {
  data() {
    return {
      list: JSON.parse(localStorage.getItem('list')) || [],
      status: obj[location.hash] || 'all', //全部'all',已完成'done',未完成'undone'
    };
  },
  methods: {
    removeItem(id) {
      const index = this.list.findIndex((item) => item.id === id);
      this.list.splice(index, 1);
    },
    changeState(id) {
      const obj = this.list.find((item) => item.id === id);
      obj.state = !obj.state;
    },
    addItem(name) {
      const id = this.list.length ? this.list.slice(-1)[0].id + 1 : 1;
      const obj = {
        id,
        name,
        state: false,
      };
      this.list.push(obj);
    },
    changeAll(value) {
      this.list.forEach((item) => (item.state = value));
    },
    clearAll() {
      this.list = this.list.filter((item) => item.state === false);
    },
  },
  computed: {
    newList() {
      if (this.status === "all") {
        return this.list;
      } else if (this.status === "done") {
        return this.list.filter((item) => item.state === true);
      } else {
        return this.list.filter((item) => item.state === false);
      }
    },
  },
  watch: {
    list: {
      handler(newValue) {
        localStorage.setItem('list',JSON.stringify(newValue))
      },
      deep:true
    }
  },
  components: {
    HmHeader,
    HmMain,
    HmFooter,
  },
};
</script>

<style></style>
